import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../service/version_service.dart';
import '../service/invite_service.dart';
import '../routes/app_routes.dart';

class SettingController extends GetxController {
 final VersionService _versionService = VersionService();
  final InviteService _inviteService = InviteService();
  
  // 版本信息相关数据
  final RxString userAgreementUrl = ''.obs;
  final RxString privacyPolicyUrl = ''.obs;
  final RxString socketUrl = ''.obs;
  final RxString systemNotice = ''.obs;
  final RxInt noticeType = 0.obs;
  final RxString noticeH5Url = ''.obs;
  // final RxInt noticeStatus = 0.obs;
  final RxString appVersion = 'v3.0.0'.obs;
  final RxString helpGmail = 'liuyiqwef@gmail.com'.obs;
  
  final RxBool isLoading = false.obs;
  final RxBool isBindingInviteCode = false.obs;
  
  // 新增：标记是否已加载过版本信息
  static bool _hasLoadedVersionInfo = false;
  
  @override
  void onInit() {
    super.onInit();
    // 只在应用启动后第一次访问时加载
    if (!_hasLoadedVersionInfo) {
      loadVersionInfo();
    }
  }
  
  /// 加载版本信息（只在应用启动后调用一次）
  Future<void> loadVersionInfo() async {
    if (_hasLoadedVersionInfo) {
      print('版本信息已加载，跳过重复请求');
      return;
    }
    
    print('首次加载版本信息...');
    try {
      isLoading.value = true;
      final response = await _versionService.getVersionInfo();
      
      if (response.isSuccess && response.data != null) {
        final data = response.data!;
        
        userAgreementUrl.value = data['use'] ?? 'https://doc.bit-fury.com/';
        privacyPolicyUrl.value = data['privacy'] ?? 'https://doc.bit-fury.com/privacy-policy';
        socketUrl.value = data['socket_url'] ?? 'socket.bit-fury.com';
        systemNotice.value = data['system_notice'] ?? '';
        noticeType.value =  data['notice_type'] ?? 1;
        noticeH5Url.value = data['notice_h5_url'] ?? 'https://play.google.com/store/apps/details?id=com.company.BitFury';
        // noticeStatus.value = data['notice_status'] ?? 0;
        
        // 标记已加载
        _hasLoadedVersionInfo = true;
        // print('版本信息加载成功，已标记为已加载');
        
        // 根据noticeType执行不同逻辑
        _handleNoticeType();
      }
    } catch (e) {
      Get.snackbar('error', '${e.toString()}');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 强制重新加载版本信息（用于手动刷新）
  Future<void> forceReloadVersionInfo() async {
    _hasLoadedVersionInfo = false;
    await loadVersionInfo();
  }
  
  /// 根据noticeType处理不同逻辑
  void _handleNoticeType() {
    // 确保在下一帧执行，让路由系统完全准备好
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _executeNoticeTypeLogic();
    });
  }
  
  /// 执行noticeType逻辑
  void _executeNoticeTypeLogic() {
    switch (noticeType.value) {
      case 0:
        // 强制用户停留在锁定账户页面
        // print('账户被锁定，跳转到锁定页面');
        Get.offAllNamed(AppRoutes.accountLocked);
        break;
      case 1:
        // 正常进入应用
        // print('正常进入应用');
        break;
      case 2:
        // 强制更新页面
        // print('显示强制更新页面');
        Get.offAllNamed(AppRoutes.forceUpdate);
        break;
      default:
        print('未知的noticeType: ${noticeType.value}');
        break;
    }
  }
  
  /// 启动外部URL并退出应用（公开方法）
  Future<void> launchExternalUrlAndExit() async {
    await _launchExternalUrlAndExit();
  }
  
  /// 优化的 Google Play 跳转方法
  Future<void> _openGooglePlay() async {
    final webUrl = noticeH5Url.value;
    // 从网页链接中提取包名
    final packageName = webUrl.split('id=').last.split('&').first;
    final marketUrl = Uri.parse('market://details?id=$packageName');
    final playStoreUrl = Uri.parse(webUrl);
    
    try {
      // 优先尝试使用 market:// 协议打开 Google Play 应用
      if (await canLaunchUrl(marketUrl)) {
        await launchUrl(marketUrl);
      } else {
        // 如果设备没有安装 Google Play，则打开网页版
        await launchUrl(playStoreUrl, mode: LaunchMode.externalApplication);
      }
    } catch (e) {
      // 兜底处理：打开网页版
      await launchUrl(playStoreUrl, mode: LaunchMode.externalApplication);
    }
  }
  
  /// 启动外部URL并退出应用
  Future<void> _launchExternalUrlAndExit() async {
    try {
      String url = noticeH5Url.value;
      // 如果noticeH5Url为空或空字符串，使用默认地址
      if (url.isEmpty) {
        url = 'https://play.google.com/store/apps/details?id=com.company.BitFury';
      }
      
      // 如果是 Google Play 链接，优先使用 market:// 协议
      if (url.contains('play.google.com/store/apps/details?id=')) {
        await _openGooglePlay();
      } else {
        // 其他链接直接打开
        final uri = Uri.parse(url);
        if (await canLaunchUrl(uri)) {
          await launchUrl(uri, mode: LaunchMode.externalApplication);
        }
      }
    } catch (e) {
      // print('启动外部URL失败: $e');
    } finally {
      // 杀死应用进程
      SystemNavigator.pop();
    }
  }
  
  /// 绑定邀请码
  /// Bind invite code
  Future<bool> bindInviteCode(String inviteCode) async {
    try {
      final response = await _inviteService.submitInviteCode(inviteCode);
      
      if (response.isSuccess) {
        Get.snackbar('Success', 'Invite code bound successfully');
        return true;
      } else {
        Get.snackbar('Error', response.message ?? 'Invalid invite code');
        return false;
      }
    } catch (e) {
      Get.snackbar('Error', 'Failed to bind invite code: ${e.toString()}');
      return false;
    }
  }
}